import React, {Fragment} from 'react'
import PropTypes from 'prop-types'
import {Button, Cascader, Col, Form, Input, message, Modal, Popconfirm, Row, Table} from 'antd'
import moment from 'moment'
import styles from './style.less'
import Position from "utils/position"


class AddressModal extends React.Component {
  index = 0
  cacheOriginData = {}

  constructor (props) {
    super(props)
    const {list} = props
    this.state = {
      list,
    }
  }

  componentWillReceiveProps (props) {
    const {list} = props
    let {list: olist} = this.state
    if (list !== olist) {
      list.forEach(i => {
        const exists = olist.filter(j => (i.id === j.id))
        if (exists.length === 0) {
          olist.push(i)
        }
      })
      olist = olist.filter(i => i.id.indexOf('NEW_') < 0)
      console.log(olist)
      this.setState({list: olist})
    }
  }

  getRowByKey (key, newData) {
    const {list} = this.state
    return (newData || list).filter(item => item.id === key)[0]
  }

  toggleEditable = (e, key) => {
    e.preventDefault()
    const {list} = this.state
    const newList = list.map(item => ({...item}))
    const target = this.getRowByKey(key, newList)
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[key] = {...target}
      }
      target.editable = !target.editable
      this.setState({list: newList})
    }
  }

  newAddress = () => {
    const {customerId} = this.props
    const {list} = this.state
    const newList = list.map(_ => ({..._}))
    newList.push({
      id: `NEW_TMP_ID_${this.index}`,
      customerId,
      editable: true,
      isNew: true,
    })
    this.index += 1
    this.setState({list: newList})
  }

  saveRow (e, key) {
    e.persist()
    this.setState({
      loading: true,
    })
    setTimeout(() => {
      if (this.clickedCancel) {
        this.clickedCancel = false
        return
      }
      const target = this.getRowByKey(key) || {}
      if (!target.provinceId || !target.receiver || !target.mobile) {
        message.error('请填写完整地址信息。')
        e.target.focus()
        this.setState({
          loading: false,
        })
        return
      }
      delete target.isNew
      target.dmobile = target.mobile.substring(0, 3) + "******" + target.mobile.substring(target.mobile.length - 2)
      this.toggleEditable(e, key)
      this.setState({
        loading: false,
      })
      const {onSave} = this.props
      onSave(target)
    }, 500)
  }

  remove (key) {
    const {list} = this.state
    const newList = list.filter(item => item.id !== key)
    this.setState({list: newList})
    // onDelete(key)
  }

  handleKeyPress (e, key) {
    if (e.key === 'Enter') {
      this.saveRow(e, key)
    }
  }

  handleFieldChange (e, fieldName, key) {
    const {list} = this.state
    const newList = list.map(item => ({...item}))
    const target = this.getRowByKey(key, newList)
    if (target) {
      target[fieldName] = e.target.value
      this.setState({list: newList})
    }
  }

  cancel (e, key) {
    this.clickedCancel = true
    e.preventDefault()
    const {list} = this.state
    const newList = list.map(item => ({...item}))
    const target = this.getRowByKey(key, newList)
    if (this.cacheOriginData[key]) {
      Object.assign(target, this.cacheOriginData[key])
      delete this.cacheOriginData[key]
    }
    target.editable = false
    this.setState({list: newList})
    this.clickedCancel = false
  }

  render () {
    const {
      handleSelect,
      item = {},
      onOk,
      loading,
      form: {
        validateFields,
        getFieldsValue,
      },
      ...modalProps
    } = this.props
    const {list} = this.state
    const handleOk = () => {
      validateFields((errors) => {
        if (errors) {
          return
        }
        const data = {
          ...getFieldsValue(),
          key: item.key,
        }
        if (data.birthDay) {
          data.birthDay = moment(data.birthDay).format('YYYY-MM-DD')
        }
        onOk(data)
      })
    }

    const modalOpts = {
      ...modalProps,
      onOk: handleOk,
    }

    const listProps = {
      rowKey: 'id',
      dataSource: list,
      loading: loading.effects['createOrder/queryAddress'],
      pagination: false,
    }

    const columns = [
      {
        title: '收货人',
        dataIndex: 'receiver',
        key: 'receiver',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                style={{width: '50%'}}
                size={'small'}
                value={text}
                onChange={e => this.handleFieldChange(e, 'receiver', record.id)}
                onKeyPress={e => this.handleKeyPress(e, record.id)}
                placeholder="收货人姓名"
              />
            )
          }
          return text
        },
      }, {
        title: '收货电话',
        dataIndex: 'dmobile',
        key: 'dmobile',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                style={{width: '60%'}}
                size={'small'}
                value={record.mobile}
                onChange={e => this.handleFieldChange(e, 'mobile', record.id)}
                onKeyPress={e => this.handleKeyPress(e, record.id)}
                placeholder="收货联系电话"
              />
            )
          }
          return text
        },
      }, {
        title: '收货地址',
        dataIndex: 'address',
        key: 'address',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Fragment>
                <Cascader
                  defaultValue={record.provinceId ? [record.provinceId, record.cityId, record.areaId] : undefined}
                  style={{width: '40%'}}
                  size={'small'}
                  allowClear
                  options={Position}
                  placeholder="请选择城市"
                  onChange={(values, options) => {
                    const newList = list.map(_ => ({..._}))
                    const target = this.getRowByKey(record.id, newList)
                    const province = options[0]
                    target['provinceId'] = province.value
                    target['provinceName'] = province.label
                    const city = options[1]
                    target['cityId'] = city.value
                    target['cityName'] = city.label
                    const area = options[2]
                    target['areaId'] = area.value
                    target['areaName'] = area.label
                    this.setState({list: newList})
                  }}
                  onKeyPress={e => this.handleKeyPress(e, record.id)}
                />
                <Input
                  style={{width: '60%'}}
                  size={'small'}
                  value={text}
                  onChange={e => this.handleFieldChange(e, 'address', record.id)}
                  onKeyPress={e => this.handleKeyPress(e, record.id)}
                  placeholder="详细地址"
                />
              </Fragment>
            )
          }
          return record.provinceName + record.cityName + record.areaName + text
        },
      }, {
        title: '操作',
        key: 'operation',
        render: (_, record) => {
          if (record.editable) {
            if (record.isNew) {
              return (
                <span>
                  <Button className={'margin-right'} onClick={e => this.saveRow(e, record.id)} type={'primary'} ghost
                          size={'small'}>添加</Button>
                  <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.id)}>
                    <Button type={'danger'} ghost size={'small'}>删除</Button>
                  </Popconfirm>
                </span>
              )
            }
            return (
              <span>
                <Button className={'margin-right'} onClick={e => this.saveRow(e, record.id)} type={'primary'} ghost
                        size={'small'}>保存</Button>
                <Button onClick={e => this.cancel(e, record.id)} type={'primary'} ghost size={'small'}>取消</Button>
              </span>
            )
          }
          return (
            <span>
              <Button onClick={e => this.toggleEditable(e, record.id)}
                      className={'margin-right'} type={'primary'} ghost size={'small'}>编辑</Button>
              <Button onClick={() => handleSelect(record)} type={'primary'}
                      className={'margin-right'} size={'small'}>选择地址</Button>
            </span>
          )
        },
      },
    ]

    return (
      <Modal {...modalOpts}>
        <Row gutter={24}>
          <Col span={24}>
            <Table
              {...listProps}
              scroll={{x: 800}}
              columns={columns}
              simple
              rowKey={record => record.id}
              rowClassName={record => (record.editable ? styles.editable : '')}
            />
            <Button
              style={{width: '100%', marginTop: 16, marginBottom: 8}}
              type="dashed"
              onClick={this.newAddress}
              icon="plus"
            >
              新增地址
            </Button>
          </Col>
        </Row>
      </Modal>
    )
  }
}

AddressModal.propTypes = {
  form: PropTypes.object.isRequired,
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default Form.create()(AddressModal)
